package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapepr;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.customer.service.IWorkerCertificationAuditService;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author:zhq
 * @Date: 2025/09/17 17:21
 * @Description:
 */
@Service
public class WorkerCertificationAuditServiceImpl extends ServiceImpl<WorkerCertificationAuditMapepr, WorkerCertificationAudit> implements IWorkerCertificationAuditService {



    @Resource
    private IWorkerCertificationService workerCertificationService;

    @Resource
    private IServeProviderService serveProviderService;
    /**
     * 实名认证
     *
     * @param workerCertificationAuditAddReqDTO 实名认证参数
     */
    @Transactional
    @Override
    public void realNameAuthentication(WorkerCertificationAuditAddReqDTO workerCertificationAuditAddReqDTO) {
        //判断身份证是否存在
        WorkerCertificationAudit workerCertificationAudit = baseMapper.selectOne(new LambdaQueryWrapper<WorkerCertificationAudit>().eq(WorkerCertificationAudit::getIdCardNo, workerCertificationAuditAddReqDTO.getIdCardNo()));
        if (workerCertificationAudit != null) {
            throw new RuntimeException("身份证已注册");
        }
        //添加认证申请
        WorkerCertificationAudit newWorkerCertificationAudit = new WorkerCertificationAudit();
        BeanUtil.copyProperties(workerCertificationAuditAddReqDTO, newWorkerCertificationAudit);
        if (ObjectUtil.isNotEmpty(workerCertificationAuditAddReqDTO.getServeProviderId())) {
            newWorkerCertificationAudit.setServeProviderId(workerCertificationAuditAddReqDTO.getServeProviderId());
        }
        newWorkerCertificationAudit.setAuditStatus(CertificationStatusEnum.INIT.getStatus());
        newWorkerCertificationAudit.setCertificationStatus(1);
        newWorkerCertificationAudit.setCreateTime(LocalDateTime.now());
        Long serveProviderId = UserContext.currentUserId();
        newWorkerCertificationAudit.setServeProviderId(serveProviderId);
        this.save(newWorkerCertificationAudit);
        //插入服务人员认证信息表
        WorkerCertification workerCertification = BeanUtils.copyBean(newWorkerCertificationAudit, WorkerCertification.class);
        workerCertification.setCreateTime(LocalDateTime.now());
        workerCertification.setId(newWorkerCertificationAudit.getServeProviderId());
        workerCertification.setCertificationStatus(1);
        workerCertificationService.save(workerCertification);
    }


    /**
     * 分页查询
     *
     * @param workerCertificationAuditPageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<WorkerCertificationAudit> pageQuery(WorkerCertificationAuditPageQueryReqDTO workerCertificationAuditPageQueryReqDTO) {
        //分页
        Page<WorkerCertificationAudit> page = PageUtils.parsePageQuery(workerCertificationAuditPageQueryReqDTO, WorkerCertificationAudit.class);

        lambdaQuery().eq(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getAuditStatus()), WorkerCertificationAudit::getAuditStatus, workerCertificationAuditPageQueryReqDTO.getAuditStatus())
                .eq(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getCertificationStatus()), WorkerCertificationAudit::getCertificationStatus, workerCertificationAuditPageQueryReqDTO.getCertificationStatus())
                .like(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getName()), WorkerCertificationAudit::getName, workerCertificationAuditPageQueryReqDTO.getName())
                .eq(ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getIdCardNo()), WorkerCertificationAudit::getIdCardNo, workerCertificationAuditPageQueryReqDTO.getIdCardNo())
                .page(page);


        if (ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getOrderBy1())) {
            page.addOrder(new OrderItem(workerCertificationAuditPageQueryReqDTO.getOrderBy1(), workerCertificationAuditPageQueryReqDTO.getIsAsc1()));
        }
        if (ObjectUtil.isNotEmpty(workerCertificationAuditPageQueryReqDTO.getOrderBy2())) {
            page.addOrder(new OrderItem(workerCertificationAuditPageQueryReqDTO.getOrderBy2(), workerCertificationAuditPageQueryReqDTO.getIsAsc2()));
        }
        PageResult<WorkerCertificationAudit> pageResult = new PageResult<>();
        pageResult.setPages(page.getPages());
        pageResult.setTotal(page.getTotal());
        pageResult.setList(page.getRecords());



        return pageResult;
    }
    /**
     * 认证审核
     * @param id
     * @param certificationAuditReqDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void auditCertification(String id, CertificationAuditReqDTO certificationAuditReqDTO) {
        //根据id查询认证申请
        WorkerCertificationAudit workerCertificationAudit = baseMapper.selectById(id);
        if (workerCertificationAudit == null) {
            throw new RuntimeException("认证申请不存在");
        }
        //更新认证审核表
        workerCertificationAudit.setAuditStatus(1);
        workerCertificationAudit.setCertificationStatus(certificationAuditReqDTO.getCertificationStatus());
        workerCertificationAudit.setRejectReason(certificationAuditReqDTO.getRejectReason());
        workerCertificationAudit.setAuditorName(UserContext.getCurrentUser().getName());
        workerCertificationAudit.setAuditorId(UserContext.currentUserId());
        baseMapper.updateById(workerCertificationAudit);
        //更新服务人员认证信息表
        workerCertificationService.update(new LambdaUpdateWrapper<WorkerCertification>()
                .eq(WorkerCertification::getId,workerCertificationAudit.getServeProviderId())
                .set(WorkerCertification::getId,workerCertificationAudit.getServeProviderId())
                .set(WorkerCertification::getCertificationStatus,certificationAuditReqDTO.getCertificationStatus())
                .set(WorkerCertification::getCertificationTime,LocalDateTime.now())
                .set(WorkerCertification::getUpdateTime,LocalDateTime.now())
        );
        if (certificationAuditReqDTO.getCertificationStatus() == 2) {
            //认证成功，更新服务人员表
            serveProviderService.update(new LambdaUpdateWrapper<ServeProvider>()
                            .eq(ServeProvider::getId,workerCertificationAudit.getServeProviderId())
                    .set(ServeProvider::getSettingsStatus,1)
            );
        }

    }

    @Override
    public RejectReasonResDTO rejectReason() {
        Long id = UserContext.currentUserId();
        WorkerCertificationAudit one = this.lambdaQuery().eq(WorkerCertificationAudit::getServeProviderId, id).one();
        return one.getRejectReason().isEmpty() ? new RejectReasonResDTO(""): new RejectReasonResDTO(one.getRejectReason());
    }
}
